from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.api import deps
from app.schemas import airport
from app.database.models.erp import Airport
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[airport.Airport])
def list_airports(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取机场列表"""
    airports = db.query(Airport).offset(skip).limit(limit).all()
    return airports

@router.post("/", response_model=airport.Airport)
def create_airport(
    *,
    db: Session = Depends(deps.get_db),
    airport_in: airport.AirportCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新机场"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    # 检查代码是否已存在
    if db.query(Airport).filter(Airport.Code == airport_in.Code).first():
        raise HTTPException(
            status_code=400,
            detail="Airport code already registered"
        )
    
    airport = Airport(**airport_in.dict())
    db.add(airport)
    db.commit()
    db.refresh(airport)
    return airport

@router.get("/{airport_id}", response_model=airport.Airport)
def get_airport(
    airport_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定机场信息"""
    airport = db.query(Airport).filter(Airport.AirportId == airport_id).first()
    if not airport:
        raise HTTPException(status_code=404, detail="Airport not found")
    return airport

@router.put("/{airport_id}", response_model=airport.Airport)
def update_airport(
    *,
    db: Session = Depends(deps.get_db),
    airport_id: int,
    airport_in: airport.AirportUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新机场信息"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    airport = db.query(Airport).filter(Airport.AirportId == airport_id).first()
    if not airport:
        raise HTTPException(status_code=404, detail="Airport not found")
    
    for field, value in airport_in.dict(exclude_unset=True).items():
        setattr(airport, field, value)
    
    # 重新计算FullName
    if any(field in airport_in.dict(exclude_unset=True) 
           for field in ['CityPinYin', 'CityName', 'Name']):
        pinyin_first = airport.CityPinYin[0].upper() if airport.CityPinYin else ''
        airport.FullName = f"{pinyin_first} {airport.CityName}{airport.Name}"
    
    db.add(airport)
    db.commit()
    db.refresh(airport)
    return airport

@router.delete("/{airport_id}")
def delete_airport(
    *,
    db: Session = Depends(deps.get_db),
    airport_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除机场"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    airport = db.query(Airport).filter(Airport.AirportId == airport_id).first()
    if not airport:
        raise HTTPException(status_code=404, detail="Airport not found")
    
    db.delete(airport)
    db.commit()
    return {"ok": True} 